

<template>
  <view class="Mall4j container">
    <view class="prod-list">
      <block v-for="(item, scIndex) in shopCartItemDiscounts" :key="scIndex">
        <view :class="'prod-block ' + (item.chooseDiscountItemDto?'discount':'')">
          <!-- 满减提示 -->
          <view v-if="item.chooseDiscountItemDto" class="discount-tips" :hidden="!item.chooseDiscountItemDto">
            <text class="text-block">{{ wxs.parseDiscount(item.chooseDiscountItemDto.discountRule,curLang) }}</text>
            <text class="text-list">{{ wxs.parseDiscountMsg(item.chooseDiscountItemDto.discountRule,item.chooseDiscountItemDto.needAmount,item.chooseDiscountItemDto.discount,curLang) }}</text>
            <text v-if="item.chooseDiscountItemDto.reduceAmount>0" class="text-list reduce-amount">{{ i18n.haveDiscount }} ￥{{ wxs.parsePrice(item.chooseDiscountItemDto.reduceAmount)[0] }}.{{ wxs.parsePrice(item.chooseDiscountItemDto.reduceAmount)[1] }}</text>
          </view>

          <!-- 商品item -->
          <block v-for="(prod, index) in item.shopCartItems" :key="index">
            <view class="goods-item">
              <view class="item">
                <view class="btn">
                  <label>
                    <checkbox :data-scindex="scIndex" :data-index="index" :value="toString(prod.prodId)" :checked="prod.checked" color="#FF6D13" @tap="onSelectedItem" />
                  </label>
                </view>
                <view class="prodinfo">
                  <view class="pic" :data-prodid="prod.prodId" @tap="toProdPage">
                    <image v-if="prod.pic" :src="prod.pic" mode="aspectFit" />
                    <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png"  mode="aspectFit" />
                  </view>
                  <view class="opt">
                    <view class="prod-name">{{ prod.prodName }}</view>
                    <view class="prod-center-row">
                      <view :class="'prod-info-text ' + (prod.skuName?'':'empty-n')" @tap.stop="getSkuListByProdId(prod)">{{ prod.skuName }}</view>
                      <view v-if="prod.discounts.length>0" class="prod-discount">
                        <text class="prod-discount-tit" @tap="onChooseDiscount(prod.basketId,prod.discountId,prod.discounts,prod.checked)">{{ wxs.getCurrDiscountName(prod.discountId,prod.discounts,curLang) }}</text>
                      </view>
                    </view>
                    <view class="price-count">
                      <view class="price">
                        <text class="symbol">￥</text>
                        <text class="big-num">{{ wxs.parsePrice(prod.price)[0] }}</text>
                        <text class="small-num">.{{ wxs.parsePrice(prod.price)[1] }}</text>
                      </view>
                      <view class="m-numSelector">
                        <view class="minus" :data-scindex="scIndex" :data-index="index" @tap="onCountMinus" />
                        <input class="backf5" type="number" :value="prod.prodCount" disabled></input>
                        <view class="plus" :data-scindex="scIndex" :data-index="index" @tap="onCountPlus" />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </block>
        </view>
      </block>
    </view>

    <view v-if="shopCartItemDiscounts.length==0" class="empty">
      <view class="img">
        <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/tabbar/basket.png" />
      </view>
      <view class="txt">{{ i18n.noAddedProductsYet }}</view>
    </view>

    <!-- 底部按钮 -->
    <view v-if="shopCartItemDiscounts.length>0" class="cart-footer">
      <view class="btn all clal_ad">
        <label @tap="onSelAll">
          <checkbox :checked="allChecked" color="#ADADAD;" />{{ i18n.selectAll }}
        </label>
      </view>
      <view class="btn del" @tap="onDelBasket">
        <text>{{ i18n.delete }}</text>
      </view>
      <view class="btn total" @tap="showPriDet">
        <view class="total-con">
          <view class="finally">
            <text class="blod">{{ i18n.total }}:</text>
            <view class="price">
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(finalMoney)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(finalMoney)[1] }}</text>
            </view>
          </view>
          <view v-if="subtractMoney>0" class="total-msg">
            <!-- 总额:￥{{wxs.toPrice(totalMoney)}} -->{{ i18n.instantReduction }}:￥{{ wxs.toPrice(subtractMoney) }}
          </view>
        </view>
        <view class="arrow-icon">
          <image v-if="hidePriModal" src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/down-arrow.png" />
          <image v-if="!hidePriModal" src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/up-arrow.png" />
        </view>
      </view>
      <view class="btn settle" @tap="toFirmOrder">
        <text>{{ i18n.settlement }}</text>
      </view>
    </view>
    <!-- end 底部按钮 -->
    <!-- 底部活动选择弹框 -->
    <view class="modals modals-bottom-dialog" :hidden="hideModal">
      <view class="modals-cancel" @tap="hideModalFun" />
      <view class="bottom-dialog-body bottom-pos radius" :animation="animationData">
        <view class="discount-title radius">{{ i18n.selectPromotion }}</view>
        <view class="radio-group">
          <radio-group v-if="reDraw" @change="radioChange">
            <label v-for="(item, index) in prodDiscounts" :key="index">
              <view class="radio-item">
                <radio color="#FF6D13" :value="String(item.discountId)" :checked="item.discountId==discountId" />
                <view class="radio-text">
                  {{ item.discountName }}
                </view>
              </view>
            </label>
            <label>
              <view class="radio-item">
                <radio color="#FF6D13" value="-1" :checked="discountId==-1" />
                <view class="radio-text">
                  {{ i18n.notPromotion }}
                </view>
              </view>
            </label>
          </radio-group>
        </view>
      </view>
    </view>

    <!-- 底部金额明细弹框 -->
    <view class="pri-modal modals-bottom-dialog" :hidden="hidePriModal">
      <view class="modals-cancel" @tap="hidePriModalFun" />
      <view class="bottom-dialog-box bottom-pos radius" :animation="animationData">
        <view class="discount-title radius">{{ i18n.amountDetails }}</view>
        <view class="price-detail">
          <view class="price-detail-item">
            <view class="det-tit">{{ i18n.comTotal }}</view>
            <view class="det-num">￥{{ wxs.toPrice(totalMoney) }}</view>
          </view>
          <view v-if="subtractMoney > 0" class="price-detail-item">
            <view class="det-tit">{{ i18n.promotionalDiscount }}</view>
            <view class="det-num">-￥{{ wxs.toPrice(subtractMoney) }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- sku弹窗组件 -->
    <prod-sku-select v-if="showSkuPop && currentProdItem.skuList" :pic="currentProdItem.pic" :least-num="currentProdItem.leastNum" :sku-id="currentProdItem.skuId" :sku-name="currentProdItem.skuName" :sku-list="currentProdItem.skuList" :is-basket="true" @setSku="handleSetSku" @closeSkuPop="handleCloseSkuPop" />
  </view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.wxs"></script>

<script>
import prodSkuSelect from '../../components/prod-sku-select/index.vue'
// pages/basket/basket.js
var http = require("../../utils/http.js");
var util = require("../../utils/util.js");
const Big = require("../../utils/big.min.js");

export default {
  components: {
    prodSkuSelect
  },
  data () {
    return {
      // picDomain: config.picDomain,
      shopCartItemDiscounts: [],
      finalMoney: 0,
      totalMoney: 0,
      subtractMoney: 0,
      allChecked: false,
      hideModal: true,
      //模态框的状态  true-隐藏  false-显示
      animationData: {},
      prodDiscounts: [],
      discountId: 0,
      basketId: 0,
      hidePriModal: true, //金额明细模态框的状态  true-隐藏  false-显示
      shopCartOrders: [],
      reDraw: true,
      basketReqData: [], // 请求购物车的数据
      curBasketItemCheck: false, // 切换满减活动时商品是否勾选
      curLang: uni.getStorageSync('lang'), // 当前语言
      // 切换sku弹窗显隐
      showSkuPop: false,
      // 当前操作的项商品
      currentProdItem: {}
    };
  },
  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    util.transTabbar();
    uni.setNavigationBarTitle({
      title: this.i18n.shoppingCart2
    });

    if (!uni.getStorageSync('token')) {
      this.shopCartOrders = []
      util.removeTabBadge()
    }
    this.loadBasketData(null);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      shopCartOrders: []
    });
  },
  methods: {
    /**
     * 根据商品id获取skuList
     * @param {Object} prod 当前要修改的选项
     */
    getSkuListByProdId (prod) {
      this.currentProdItem = prod
      const params = {
        url: '/prod/skuList',
        method: 'GET',
        data: {
          prodId: prod.prodId
        },
        callBack: res => {
          this.currentProdItem.skuList = res
          this.showSkuPop = true
        },
        errCallBack: errMsg => {
          console.log(errMsg)
        }
      }
      http.request(params)
    },

    /**
    * 隐藏sku弹窗
    */
    handleCloseSkuPop () {
      this.showSkuPop = false
    },

    /**
     * 修改商品的sku
     */
    handleSetSku (sku) {
      const currentProdItem = this.currentProdItem
      const params = {
        basketId: currentProdItem.basketId,
        count: 0,
        shopId: currentProdItem.shopId,
        prodId: currentProdItem.prodId,
        skuId: sku.skuId
      }
      this.updateBasket(params)
    },

    /**
     * 更新购物车
     * @param {Object} updateBasketParam 请求的参数
     */
    updateBasket (updateBasketParam) {
      if (updateBasketParam.count == -1 && this.currentProdItem.prodCount == 1) {
        return
      }
      const params = {
        url: '/p/shopCart/changeShopCartSku',
        method: 'PUT',
        data: updateBasketParam,
        callBack: res => {
          const discountData = {
            basketId: updateBasketParam.basketId,
            discountId: updateBasketParam.discountId
          }
          this.loadBasketData(discountData)
          if (updateBasketParam.count && updateBasketParam.count >= 1) {
            const flowAnalysisLogDto = uni.getStorageSync('flowAnalysisLogDto')
            flowAnalysisLogDto.bizData = updateBasketParam.prodId
            flowAnalysisLogDto.bizType = 0
            uni.setStorageSync('flowAnalysisLogDto', flowAnalysisLogDto)
            util.tapLog(4, '', '', updateBasketParam.count)
          }
          this.showSkuPop = false
        }
      }
      http.request(params)
    },

    /**
     * 关闭弹窗
     */
    closePop () {
      this.hideModal = true
      this.hidePriModal = true
    },
    /**
     * 加载购物车
     */
    loadBasketData (discountData) {
      var reqData = [];
      var shopCartIds = [];
      if (discountData) {
        this.basketReqData.forEach((item, index) => {
          if (item.basketId == discountData.basketId) {
            this.basketReqData.splice(index, 1)
          }
        })
        reqData.push(discountData)
      }
      reqData = [...this.basketReqData, ...reqData]
      if (this.shopCartItemDiscounts.length) {
        this.shopCartItemDiscounts.forEach(cItems => {
          cItems.shopCartItems.forEach(pItem => {
            if (pItem.checked) {
              shopCartIds.push(pItem.basketId);
            }
          })
        })
      }
      var params = {
        url: "/p/shopCart/info",
        method: "POST",
        data: reqData,
        callBack: res => {
          if (res.length > 0) {
            var shopCartItemDiscounts = res[0].shopCartItemDiscounts;
            if (shopCartIds.length == 0) {
              this.setData({
                shopCartItemDiscounts: shopCartItemDiscounts,
              })
            } else {
              var checkedLog = [] // 之前勾选的basketId数组
              this.shopCartItemDiscounts.forEach(shopCartItem => {
                shopCartItem.shopCartItems.forEach(shopCartItem => {
                  if (shopCartItem.checked) {
                    checkedLog.push(shopCartItem.basketId)
                  }
                })
              })
              shopCartItemDiscounts.forEach(nShopCartItem => {
                nShopCartItem.shopCartItems.forEach(nShopCartItem => {
                  if (checkedLog.includes(nShopCartItem.basketId)) {
                    nShopCartItem.checked = true
                  }
                })
              })
              this.setData({
                shopCartItemDiscounts: shopCartItemDiscounts
              })
            }
          } else {
            this.setData({
              shopCartItemDiscounts: []
            });
          }
          this.checkAllSelected() // 检查全选状态
          this.calTotalPrice(); //计算总价
        }
      };
      http.request(params);
      http.getCartCount(); //重新计算购物车总数量
    },

    /**
     * 去结算
     */
    toFirmOrder: function () {
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var basketIds = [];
      shopCartItemDiscounts.forEach(shopCartItemDiscount => {
        shopCartItemDiscount.shopCartItems.forEach(shopCartItem => {
          if (shopCartItem.checked) {
            basketIds.push(shopCartItem.basketId);
          }
        });
      });

      if (!basketIds.length) {
        uni.showToast({
          title: this.i18n.selectProduct,
          icon: "none"
        });
        return;
      }

      wx.setStorageSync("basketIds", JSON.stringify(basketIds));
      uni.navigateTo({
        url: '/pages/submit-order/submit-order?orderEntry=0'
      });
    },

    /**
     * 全选
     */
    onSelAll: function () {
      var allChecked = this.allChecked;
      allChecked = !allChecked; //改变状态
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          cItems[j].checked = allChecked;
          if (allChecked) {
            this.basketReqData.push({
              basketId: cItems[j].basketId,
              discountId: '',
              isCheck: allChecked
            })
          } else {
            this.basketReqData = []
          }
        }
      }
      this.setData({
        allChecked: allChecked,
        shopCartItemDiscounts: shopCartItemDiscounts
      });
      this.loadBasketData()
    },

    /**
     * 每一项的选择事件
     */
    onSelectedItem: function (e) {
      var index = e.currentTarget.dataset.index; // 获取data- 传进来的index
      var scindex = e.currentTarget.dataset.scindex;
      var shopCartItemDiscounts = this.shopCartItemDiscounts; // 获取购物车列表
      var checked = shopCartItemDiscounts[scindex].shopCartItems[index].checked; // 获取当前商品的选中状态
      shopCartItemDiscounts[scindex].shopCartItems[index].checked = !checked; // 改变状态
      this.setData({
        shopCartItemDiscounts: shopCartItemDiscounts
      });
      if (shopCartItemDiscounts[scindex].shopCartItems[index].checked) {
        this.basketReqData.push({
          basketId: shopCartItemDiscounts[scindex].shopCartItems[index].basketId,
          discountId: shopCartItemDiscounts[scindex].shopCartItems[index].discountId,
          isCheck: true
        })
      } else {
        var sliceIndex = null
        this.basketReqData.forEach((el, index2) => {
          if (el.basketId == shopCartItemDiscounts[scindex].shopCartItems[index].basketId && el.discountId == shopCartItemDiscounts[scindex].shopCartItems[index].discountId) {
            sliceIndex = index2
          }
        })
        this.basketReqData.splice(sliceIndex, 1)
      }
      this.loadBasketData()
    },

    /**
     * 检查全选状态
     */
    checkAllSelected: function () {
      var allChecked = true;
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var flag = false;
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          if (!cItems[j].checked) {
            allChecked = !allChecked;
            flag = true;
            break;
          }
        }
        if (flag) {
          break;
        }
      }
      this.setData({
        allChecked: allChecked
      });
    },

    /**
     * 计算购物车总额
     */
    calTotalPrice: function () {
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var shopCartIds = [];
      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;
        for (var j = 0; j < cItems.length; j++) {
          if (cItems[j].checked) {
            shopCartIds.push(cItems[j].basketId);
          }
        }
      }
      var ths = this;
      var params = {
        url: "/p/shopCart/totalPay",
        method: "POST",
        data: shopCartIds,
        callBack: function (res) {
          ths.setData({
            finalMoney: res.finalMoney,
            totalMoney: res.totalMoney,
            subtractMoney: res.subtractMoney
          });
        }
      };
      http.request(params);
    },

    /**
     * 减少数量
     */
    onCountMinus: function (e) {
      var index = e.currentTarget.dataset.index;
      var scindex = e.currentTarget.dataset.scindex;
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var prodCount = shopCartItemDiscounts[scindex].shopCartItems[index].prodCount;

      if (prodCount > 1) {
        this.updateCount(shopCartItemDiscounts, scindex, index, -1);
      }
    },

    /**
     * 增加数量
     */
    onCountPlus: function (e) {
      var index = e.currentTarget.dataset.index;
      var scindex = e.currentTarget.dataset.scindex;
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      this.updateCount(shopCartItemDiscounts, scindex, index, 1);
    },

    /**
     * 改变购物车数量接口
     */
    updateCount: function (shopCartItemDiscounts, scindex, index, prodCount) {
      var ths = this;
      var params = {
        url: "/p/shopCart/changeItem",
        method: "POST",
        data: {
          count: prodCount,
          prodId: shopCartItemDiscounts[scindex].shopCartItems[index].prodId,
          skuId: shopCartItemDiscounts[scindex].shopCartItems[index].skuId,
          shopId: 1
        },
        callBack: function (res) {
          shopCartItemDiscounts[scindex].shopCartItems[index].prodCount += prodCount;
          ths.setData({
            shopCartItemDiscounts: shopCartItemDiscounts
          });
          var discountData = null
          if (shopCartItemDiscounts[scindex].shopCartItems[index].checked) {
            discountData = {
              basketId: shopCartItemDiscounts[scindex].shopCartItems[index].basketId,
              discountId: shopCartItemDiscounts[scindex].shopCartItems[index].discountId,
              isCheck: true
            }
          }
          ths.loadBasketData(discountData)
        }
      };
      http.request(params);
      if (prodCount >= 1) {
        const flowAnalysisLogDto = uni.getStorageSync('flowAnalysisLogDto')
        flowAnalysisLogDto.bizData = shopCartItemDiscounts[scindex].shopCartItems[index].prodId
        flowAnalysisLogDto.bizType = 0
        uni.setStorageSync('flowAnalysisLogDto', flowAnalysisLogDto)
        util.tapLog(4, '', '', prodCount)
      }
    },

    /**
     * 删除购物车商品
     */
    onDelBasket: function () {
      var ths = this;
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var basketIds = [];

      for (var i = 0; i < shopCartItemDiscounts.length; i++) {
        var cItems = shopCartItemDiscounts[i].shopCartItems;

        for (var j = 0; j < cItems.length; j++) {
          if (cItems[j].checked) {
            basketIds.push(cItems[j].basketId);
          }
        }
      }

      if (basketIds.length == 0) {
        uni.showToast({
          title: ths.i18n.selectProduct,
          icon: "none"
        });
      } else {
        // 关闭弹窗
        this.closePop()
        uni.showModal({
          title: '',
          content: ths.i18n.deleteProductTips,
          cancelText: ths.i18n.cancel,
          confirmText: ths.i18n.confirm,
          confirmColor: "#FF6D13",
          success (res) {
            if (res.confirm) {
              var params = {
                url: "/p/shopCart/deleteItem",
                method: "put",
                data: basketIds,
                callBack: function (res) {
                  ths.loadBasketData(null);
                }
              };
              http.request(params);
            }
          }

        });
      }
    },

    /**
     * 点击满减活动 弹窗
     */
    onChooseDiscount (basketId, discountId, discounts, checked) {
      this.reDraw = false
      this.setData({
        prodDiscounts: discounts,
        hideModal: false,
        discountId: discountId ? discountId : -1, // 值不存在或者是0则赋值为-1（不参与促销）
        basketId: basketId,
        curBasketItemCheck: Boolean(checked), // 当前展示满减活动的商品是否已选中
      });
      var animation = wx.createAnimation({
        duration: 600,
        timingFunction: 'ease'
      });
      this.animation = animation;
      this.reDraw = true
      setTimeout(() => {
        this.fadeIn();
      }, 200);
    },

    radioChange (e) {
      this.loadBasketData({
        basketId: this.basketId,
        discountId: e.detail.value,
        isCheck: this.curBasketItemCheck
      });
      this.fadeDown()
      setTimeout(() => {
        this.setData({
          hideModal: true
        });
      }, 500)
      this.reDraw = false
    },

    // 隐藏遮罩层
    hideModalFun: function () {
      this.reDraw = false
      var that = this;
      var animation = wx.createAnimation({
        duration: 800,
        timingFunction: 'ease'
      });
      this.animation = animation;
      that.fadeDown();
      setTimeout(function () {
        that.setData({
          hideModal: true
        });
      }, 720);
    },
    //动画集
    fadeIn: function () {
      this.animation.translateY(0).step();
      this.setData({
        animationData: this.animation.export() //动画实例的export方法导出动画数据传递给组件的animation属性

      });
    },
    fadeDown: function () {
      this.animation.translateY(300).step();
      this.setData({
        animationData: this.animation.export()
      });
    },

    /**
     * 跳转到商品详情`
     */
    toProdPage (e) {
      uni.navigateTo({
        url: '/pages/prod/prod?prodid=' + e.currentTarget.dataset.prodid
      });
    },

    /**
     * 金额明细弹窗
     */
    showPriDet () {
      var that = this;

      if (this.hidePriModal == true) {
        this.setData({
          hidePriModal: false
        });
        var animation = wx.createAnimation({
          duration: 500,
          timingFunction: 'ease'
        });
        this.animation = animation;
        setTimeout(function () {
          that.fadeIn();
        }, 100);
      } else if (this.hidePriModal == false) {
        this.hidePriModalFun();
      }
    },

    hidePriModalFun () {
      var that = this;
      var animation = wx.createAnimation({
        duration: 800,
        timingFunction: 'ease'
      });
      this.animation = animation;
      that.fadeDown();
      setTimeout(function () {
        that.setData({
          hidePriModal: true
        });
      }, 680);
    }

  }
};
</script>
<style  scoped lang='scss'>
@import "./basket.scss";

</style>
